package com.sl.utils.file;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * @ProjectName: travel-report
 * @Package: com.zjhcsoft.travel.report.util
 * @ClassName: FileIUtils
 * @Author: zhangchao
 * @Description: 文件工具类
 * @Date: 2020/1/13 11:45
 * @Version: 1.0
 */
public class FileUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
    private final static String SEPARATOR = File.separator;

    /**
     * 根据byte数组，生成文件  写入文件
     * @param buffer 文件数组
     * @param filePath 文件存放路径
     */
    public static void byte2File(byte[] buffer,String filePath){
        BufferedOutputStream bos=null;
        FileOutputStream fos=null;
        File file=null;
        try{
            file=new File(filePath);
            fos=new FileOutputStream(file);
            bos=new BufferedOutputStream(fos);
            bos.write(buffer);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            try{
                if(bos != null){
                    bos.close();
                }
                if(fos != null){
                    fos.close();
                }
            }
            catch(Exception e){
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 获得指定文件的byte数组 读取文件
     * @param filePath 文件绝对路径
     * @return
     */
    public static byte[] file2Byte(String filePath){
        ByteArrayOutputStream bos=null;
        BufferedInputStream in=null;
        try{
            File file=new File(filePath);
            if(!file.exists()){
                throw new FileNotFoundException("file not exists");
            }
            bos=new ByteArrayOutputStream((int)file.length());
            in=new BufferedInputStream(new FileInputStream(file));
            int buf_size=1024;
            byte[] buffer=new byte[buf_size];
            int len=0;
            while(-1 != (len=in.read(buffer,0,buf_size))){
                bos.write(buffer,0,len);
            }
            return bos.toByteArray();
        }
        catch(Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
            return null;
        }
        finally{
            try{
                if(in!=null){
                    in.close();
                }
                if(bos!=null){
                    bos.close();
                }
            }
            catch(Exception e){
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 字符串转换成数组
     * @param hexString
     * @return
     */
    public static byte[] toByteArray(String hexString) {
        hexString = hexString.toLowerCase();
        final byte[] byteArray = new byte[hexString.length() / 2];
        int k = 0;
        // 因为是16进制，最多只会占用4位，转换成字节需要两个16进制的字符，高位在先
        for (int i = 0; i < byteArray.length; i++) {
            byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
            byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
            byteArray[i] = (byte) (high << 4 | low);
            k += 2;
        }
        return byteArray;
    }

    /**
     * 字符串写入文件
     * @param restring
     * @param filePath
     */
    public static void strToFile(String restring, String filePath){
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            fos.write(restring.getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 字符串转换成字节流并输出
     *
     */
    public void file(HttpServletResponse response, String xx){

        byte[] bytes = toByteArray(xx);
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            response.addHeader("Content-Type", "image/jpeg");
            os.write(bytes);
            os.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取文本文件
     * @param fileName
     * @return
     */
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Base64字符串转为字节数组
     * @param encodeData
     * @return
     */
    public  static byte[] baseTobyte(String encodeData) {
        byte[] data;
        try {
            //解码
            BASE64Decoder decoder = new BASE64Decoder();
            data = decoder.decodeBuffer(encodeData);
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  Base64字节数组转为文件
     * @param model
     * @throws IOException
     */
    public static void baseToFile(Map<String, Object> model) throws IOException {
        String encodeData = model.get("chartPic").toString();
        String path = model.get("path").toString();
        String dirPath = path.substring(0, path.lastIndexOf(SEPARATOR) + 1);
        FileOutputStream fos = null;
        try {
            File tempPath = new File(dirPath);
            if (!tempPath.exists()) {
                LOGGER.info("-----------------------tempPath不存在");
                tempPath.mkdirs();
                LOGGER.info("-----------------------tempPath创建成功：{}", tempPath.getPath());
            }
            byte[] fileEncode = baseTobyte(encodeData);
            fos = new FileOutputStream(path);
            fos.write(fileEncode);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fos.close();
        }
    }

    /**
     * 获取文件Base64字节码字符串
     * @param url
     * @return
     */
    public static String getImageStr(String url) throws IOException{
        InputStream in = null;
        byte[] data = null;
        File file = new File(url);
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            BASE64Encoder encoder = new BASE64Encoder();
            String encodeData = encoder.encode(data);
            return encodeData;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            in.close();
        }
        return null;
    }
}
